﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using XFControls.Utils;

namespace XFControls.XFPanels.XFPanelItems
{
    public class XFItemAnimation : XFItemBase
    {
        private int _height;
        private int _x;
        private int _y;
        private int _currFrame;
        private int _frameWidth;
        private int _numbFrames;
        private bool _alpha;

        public Bitmap StoryLine { get; set; }

        public XFItemAnimation(int height, int x, int y)
        {
            _height = height;
            _x = x;
            _y = y;
            _currFrame = 0;
            ItemType = XFItemType.Display;
        }

        public override int GetHeight()
        {
            return _height;
        }

        public override void ItemPaint(Graphics g, int x, int y)
        {
            if (StoryLine == null)
                return;

            //Calculate the left location of the drawing frame
            int XLocation = _currFrame++ * _frameWidth;
            if (_currFrame == _numbFrames)
                _currFrame = 0;

            Rectangle rect = new Rectangle(XLocation, 0, _frameWidth, StoryLine.Height);

            //Draw image
            if (_alpha)
                XFControlUtils.DrawAlphaFirstPix(g, StoryLine, _x, _y, _frameWidth, StoryLine.Height, XLocation);
            else
                g.DrawImage(StoryLine, _x, _y, rect, GraphicsUnit.Pixel);
        }

        public void SetStoryLine(string path, int frames)
        {
            _numbFrames = frames;
            try
            {
                StoryLine = XFBitmapFactory.GetBitmap(path);
                _frameWidth = StoryLine.Width / frames;

                ItemRectangle = new Rectangle(_x, _y, _frameWidth, _height);

                var file = path.Split('\\').Last();
                _alpha = file.Contains("alpha");
            }
            catch (Exception e)
            {
            }
        }

        public override void Dispose()
        {
            base.Dispose();

            if (StoryLine != null)
                StoryLine.Dispose();
        }
    }
}
